﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using IntraVision.Web;
using IntraVision.Web.Security;
using Model;

public enum PermissionGroupType : int { System = 1, Finance = 2 }

[SecurityAttribute]
public class PermissionController : EntityListController<Permission, NotarialServiceDataContext>
{
    public override void List()
    {
        RegisterScript("jquery.ui.packed.js", "status/list.js");

        base.List();
    }

    protected override void EntityLoaded(NotarialServiceDataContext dc, Permission entity)
    {
        RegisterScript("status/status.js");
    }

    protected override void BeforeSubmit(NotarialServiceDataContext dc, Permission permission)
    {
        if (Request.Files.Count == 0 && permission.Id == 0)
            throw new ArgumentException("Файл с рисунком не задан!");

        if (Request.Files["file24"] != null && Request.Files["file24"].ContentLength > 0)
        {
            var file = Request.Files["file24"];
            var fname = System.IO.Path.GetFileName(file.FileName);
            string path24 = Context.Server.MapPath(String.Format("~/img/permissions/{0}", fname));
            permission.Image24 = fname;
            file.SaveAs(path24);
        }
        if (Request.Files["file16"] != null && Request.Files["file16"].ContentLength > 0)
        {
            var file = Request.Files["file16"];
            var fname = System.IO.Path.GetFileName(file.FileName);
            string path16 = Context.Server.MapPath(String.Format("~/img/permissions/{0}", fname));
            permission.Image16 = fname;
            file.SaveAs(path16);
        }
    }

    public void SaveOrder()
    {
        int[] ids = RequestHelper.GetIdsFromString(Request["ids"]);
        int so = 1;
        try
        {
            using (var dc = new NotarialServiceDataContext())
            {
                foreach (int id in ids)
                {
                    var status = dc.Status.SingleOrDefault(s => s.Id == id);
                    if (status != null)
                    {
                        status.SortOrder = so;
                        so++;
                    }
                }
                dc.SubmitChanges();
            }
        }
        catch (Exception ex)
        {
            RenderJSON(new AJAXResult(ex));
        }
        RenderJSON(new AJAXResult());
    }
}
